#include "addeventdialog.h"
#include "ui_addeventdialog.h"
#include "databasemanager.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlError>

addeventdialog::addeventdialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::addeventdialog)
{
    ui->setupUi(this);
    loadVenues();
}

addeventdialog::~addeventdialog()
{
    delete ui;
}

void addeventdialog::loadVenues()
{
    QSqlQuery query(DatabaseManager::instance().getDatabase());
    query.exec("SELECT venue_id, name FROM Venues");

    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        ui->comboBoxVenue->addItem(name, id);
    }
}

void addeventdialog::on_buttonBox_accepted()
{
    int venueId = ui->comboBoxVenue->currentData().toInt();
    QString name = ui->lineEditName->text();
    QString type = ui->lineEditType->text();
    QString desc = ui->textEditDescription->toPlainText();
    QDate startDate = ui->dateEditStart->date();
    QDate endDate = ui->dateEditEnd->date();
    int capacity = ui->spinBoxCapacity->value();
    bool ticket = ui->checkBoxTicket->isChecked();

    if (name.isEmpty() || type.isEmpty()) {
        QMessageBox::warning(this, "错误", "活动名称和类型不能为空");
        return;
    }

    QSqlQuery query(DatabaseManager::instance().getDatabase());
    query.prepare(R"(
        INSERT INTO Exhibitions_Events (venue_id, name, type, start_date, end_date, description, capacity, ticket_required)
        VALUES (:venue_id, :name, :type, :start_date, :end_date, :description, :capacity, :ticket)
    )");
    query.bindValue(":venue_id", venueId);
    query.bindValue(":name", name);
    query.bindValue(":type", type);
    query.bindValue(":start_date", startDate);
    query.bindValue(":end_date", endDate);
    query.bindValue(":description", desc);
    query.bindValue(":capacity", capacity);
    query.bindValue(":ticket", ticket);

    if (!query.exec()) {
        QMessageBox::warning(this, "插入失败", query.lastError().text());
    } else {
        accept();
    }
}
